﻿using System;
using JetBrains.Annotations;
using JetBrains.Application;
using JetBrains.Application.Settings;
using JetBrains.ProjectModel;
using JetBrains.ProjectModel.DataContext;
using JetBrains.ProjectModel.Settings.Store;
using JetBrains.ProjectModel.Transaction;

namespace GammaJul.ReSharper.GammaXaml.Caliburn {

	public static class CaliburnSupportProperty {
		
		public static CaliburnSupport GetConfiguredCaliburnSupport([NotNull] IContextBoundSettingsStore settingsStore) {
			if (settingsStore == null)
				throw new ArgumentNullException("settingsStore");

			return settingsStore.GetValue<CaliburnProjectSettings, CaliburnSupport>(cps => cps.Support);
		}

		public static CaliburnSupport GetConfiguredCaliburnSupport([NotNull] this IProject project, [NotNull] ISettingsStore settingsStore) {
			if (project == null)
				throw new ArgumentNullException("project");
			if (settingsStore == null)
				throw new ArgumentNullException("settingsStore");

			IContextBoundSettingsStore ctxSettingsStore = settingsStore.BindToContextTransient(ContextRange.Smart(project.ToDataContext()));
			return GetConfiguredCaliburnSupport(ctxSettingsStore);
		}

		public static CaliburnSupport GetConfiguredCaliburnSupport([NotNull] this IProject project) {
			return GetConfiguredCaliburnSupport(project, project.GetComponent<ISettingsStore>());
		}

		public static void SetConfiguredCaliburnSupport([NotNull] this IProject project, CaliburnSupport value) {
			if (project == null)
				throw new ArgumentNullException("project");

			using (WriteLockCookie.Create()) {
				CaliburnSupport oldValue = project.GetConfiguredCaliburnSupport();
				if (oldValue == value)
					return;

				project
					.GetComponent<ProjectSettings>()
					.BindForWritingToProjectShared()
					.SetValue<CaliburnProjectSettings, CaliburnSupport>(cps => cps.Support, value);

				ProjectModelChangeUtil.AddPropertyChange(
					project.GetSolution().BatchChangeManager,
					project,
					typeof(CaliburnSupportProperty),
					oldValue,
					value);
			}
		}

	}

}